<template>
  <GcTable
    ref="instanceTable"
    v-model:searchKeywords="searchKeywords"
    v-loading="loading"
    :columns="TOOL_COLUMN"
    :tableData="tableData"
    :showPage="false"
    :showFilter="false"
    :spanMethod="objectSpanMethod"
    searchPlaceholder="请输入工具名称进行搜索"
    @search="handlerSearch"
    @selection-change="handlerSelectionChange">
    <template #btn-group>
      <el-button
        v-permission="'tool-list-permission:btn:add'"
        type="primary"
        @click="batchImportModalVisible = true">批量导入</el-button>
      <el-button
        v-permission="'tool-list-permission:btn:add'"
        type="primary"
        @click="currentTool = null; toolModalVisible = true">新增工具</el-button>
      <el-button
        @click="deleteTool(selectionIds)"
        :disabled="!selectionIds.length"
        v-permission="'tool-list-permission:btn:delete'"
        type="danger">批量删除</el-button>
    </template>
    <template #classifyName="{ row }">
      <p class="classify-name">
        <i :class="row.icon"></i>
        <span>{{ row.classifyName }}</span>
      </p>
    </template>
    <template #logo="{ row }">
      <el-image
        v-if="row.logo"
        :z-index="999999"
        preview-teleported
        style="width: 28px; height: 28px"
        :src="row.logo"
        :zoom-rate="1.2"
        :preview-src-list="[row.logo]"
        fit="cover"
      />
    </template>
    <template #url="{ row }">
      <p style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
        <a :href="row.url" target="_blank" style="color: #4c86ce;">{{ row.url }}</a>
      </p>
    </template>
    <template #operate="{ row }">
      <div class="operate-btn-group center">
        <gc-icon-button
          type="link"
          v-permission="'tool-list-permission:btn:edit'"
          @click="updateTool(row)">编辑</gc-icon-button>
        <gc-icon-button
          type="link"
          v-permission="'tool-list-permission:btn:delete'"
          @click="deleteTool([row.id])">删除</gc-icon-button>
      </div>
    </template>
  </GcTable>
  <OperateToolModal v-if="toolModalVisible" @close-modal="closeModal" :toolInfo="currentTool" />

  <BatchImportToolModal v-if="batchImportModalVisible" @close-modal="closeModal" />
</template>

<script setup lang="ts" name="ToolList">
import { ref } from 'vue'
import { TOOL_COLUMN } from './const'
import usePagination from '@/hooks/usePagination'
import type { Tool } from '@/http/type'
import { apiGetToolList, apiDeleteTools } from '@/http/service'
import { ElMessageBox, ElMessage, type TableColumnCtx } from 'element-plus'
import OperateToolModal from './components/OperateToolModal.vue'
import BatchImportToolModal from './components/BatchImportToolModal.vue'

interface SpanMethodProps {
  row: Tool
  column: TableColumnCtx<Tool>
  rowIndex: number
  columnIndex: number
}
const instanceTable = ref()
const searchKeywords = ref('')
const { loading } = usePagination()
const tableData = ref<Array<Tool>>([])
const currentTool = ref<null | Tool>(null)
const toolModalVisible = ref(false)
const batchImportModalVisible = ref(false)
const selectionIds = ref<Array<number>>([])
const spanList = ref<number[]>([])

/**
 * 工具列表查询
 */
async function findToolList () {
  loading.value = true
  try {
    const data = await apiGetToolList<Array<Tool>>(searchKeywords.value)
    tableData.value = data
    rowspan()
  } catch (error) {
    tableData.value = []
  } finally {
    loading.value = false
  }
}
findToolList()

function rowspan () {
  let position = 0
  spanList.value = []
  tableData.value.forEach((item, index) => {
    if (index === 0) {
      spanList.value.push(1)
      position = 0
    } else {
      if (tableData.value[index].classifyName === tableData.value[index - 1].classifyName) {
        spanList.value[position] += 1
        spanList.value.push(0)
      } else {
        spanList.value.push(1)
        position = index
      }
    }
  })
}

function objectSpanMethod ({
  rowIndex,
  columnIndex
}: SpanMethodProps) {
  if (columnIndex === 2) {
    const _row = spanList.value[rowIndex]
    const _col = _row > 0 ? 1 : 0
    return {
      rowspan: _row,
      colspan: _col
    }
  }
}

/**
 * 工具删除
 * @param ids
 */
async function deleteTool (ids: Array<number>) {
  await ElMessageBox.confirm(
    '删除工具后将无法恢复？',
    '提示',
    {
      type: 'warning'
    }
  )
  await apiDeleteTools({ ids })
  ElMessage.success('删除工具成功')
  findToolList()
}

function handlerSearch () {
  findToolList()
}

function updateTool (toolItem: Tool) {
  currentTool.value = toolItem
  toolModalVisible.value = true
}

function handlerSelectionChange (selections: Array<Tool>) {
  selectionIds.value = selections.map(o => o.id)
}

function closeModal (update?: boolean) {
  if (update) {
    findToolList()
  }
  toolModalVisible.value = false
  batchImportModalVisible.value = false
}
</script>

<style lang="scss" scoped>
:deep(.el-table__row) {
  td {
    &:nth-child(3) {
      border-left: 1px solid #f0f0f0;
      border-right: 1px solid #f0f0f0 !important;
    }
    &[rowspan='1'] {
      border-left: none !important;
      border-right: none !important;
    }
  }
}

.classify-name {
  color: #2080f7;
  i {
    font-size: 16px;
    margin-right: 6px;
    position: relative;
    top: 1px;
  }
}
</style>
